package zserver

import (
	"fmt"
	"net"
	"zinx/zinterface"
)

type ZConnector struct {
	ConnId     uint32                // 1. id
	Conn       *net.TCPConn          // 2. socket套接字
	isClosed   bool                  // 3. 当前的状态
	handlerAPI zinterface.HandleFunc // 4. 所绑定的方法
	ExitChan   chan bool             // 5. 等待连接推出的channel
}

func NewConnector(conn *net.TCPConn, id uint32, handler zinterface.HandleFunc) *ZConnector {
	zc := &ZConnector{
		ConnId:     id,
		Conn:       conn,
		isClosed:   false,
		handlerAPI: handler,
		ExitChan:   make(chan bool, 1),
	}

	return zc
}

/*
	实现iconnector接口
*/

func (zc *ZConnector) StartReader() {
	fmt.Println("Reader goroutine is running...")
	defer fmt.Println("Connection: ", zc.ConnId, " is STOPPING, RemoteAddr is: ", zc.Conn.RemoteAddr().String())
	defer zc.Stop()

	for {
		// 读取客户端发送的字节
		buf := make([]byte, 512)
		cnt, err := zc.Conn.Read(buf)
		if err != nil {
			fmt.Println("!!!ERROR When Reading From Client: ", err)
			continue
		}

		// 运行定义的handlerAPI方法
		if err = zc.handlerAPI(zc.Conn, buf, cnt); err != nil {
			fmt.Println("!!!ERROR When Running HandlerAPI: ", err)
			break
		}

	}

}

func (zc *ZConnector) Start() {
	fmt.Println("START CONNECTION: ", zc.ConnId)

	// 启动读goroutine
	go zc.StartReader()

	// TODO: 启动写goroutine

}

func (zc *ZConnector) Stop() {
	fmt.Println("Start STOP CONNECTION: ", zc.ConnId)

	if zc.isClosed {
		fmt.Println("CONNECTION ", zc.ConnId, " has already closed!")
		return
	}

	// 关闭连接，释放资源
	zc.isClosed = true

	zc.Conn.Close()

	close(zc.ExitChan)
}

func (zc *ZConnector) GetTCPConn() *net.TCPConn {
	return zc.Conn
}

func (zc *ZConnector) GetRemoteAddr() net.Addr {
	return zc.Conn.RemoteAddr()
}

func (zc *ZConnector) GetId() uint32 {
	return zc.ConnId
}

func (zc *ZConnector) IsClosed() bool {
	return zc.isClosed
}

func (zc *ZConnector) Send([]byte) error {
	// TODO:
	return nil
}
